<template>
	<view class="confirm-contain">
		<view class="confirm-order">
			<view class="confirm-con">
				<view class="confirm-address-wrap">
					<view class="title-wrap row">
						<text class="line"></text>
						<text class="bold lg">订单信息</text>
					</view>
					<view class="address-info">
						<view class="address-wrap">
							<view class="row-between">
								<text>{{address.nickName}}</text>
								<text>{{address.mobile}}</text>
							</view>
							<view class="mt10 mb10">{{address.companyName}}</view>
							<view class="address" v-show="address.id">
								{{`${address.mansionName}${address.floor}楼${address.houseNumber}`}}
							</view>
						</view>
						<view class="time-info row-between">
							<text>预计送达时间</text>
							<text>{{address.deliveryTime}}</text>
						</view>
					</view>
					<!-- <navigator hover-class="none" url="/pages/user_address/user_address?type=1">
						<address-item :address="address"></address-item>
					</navigator> -->
				</view>
				<view class="menus contain">
					<view class="title-wrap row">
						<text class="line"></text>
						<text class="bold lg">套餐信息</text>
					</view>
					<order-goods :list="menus"></order-goods>
				</view>
			</view>
			<view class="footer nr fixed">
				<!-- @tap="goPage('/pages/bundle/coupon_select/coupon_select')" -->
				<view class="item row-between" @tap="changeShowPop">
					<view>优惠券({{couponNum}})</view>
					<view class="coupon-num">
						<text v-if="couponNum">
							{{orderInfo.couponAmount ? `-${orderInfo.couponAmount} 元`: "去使用"}}
						</text>
						<text style="color: #b7b7b7;" v-else>无可用优惠券</text>
					</view>
				</view>
				<view class="row-between all-price-wrap">
					<view class="all-price row">
						<text>合计:¥ </text>
						<view class="primary row-between">
							<price-format class="primary-wrap" :first-size="48" :second-size="48" color="#FF6600"
								:price="orderInfo.order_amount" :weight="600" unitField=" ">
							</price-format>
							<price-format class="muted" :firstSize="24" :secondSize="24" :subscript-size="24"
								line-through :price="actualPrice" :weight="600" unitField="-">
							</price-format>
							<text class="muted unit-text">元</text>
						</view>
					</view>
					<button class="btn br60 white" size="md" hover-class="none" @tap="onSubmitOrder">
						下单
					</button>
				</view>
			</view>
		</view>
		<u-popup class="coupon-pop" v-model="showPop" :mask-close-able="false" mode="bottom" border-radius="14"
			height="60%">
			<my-coupons type="2" @getnum="onChangeNum($event)" @getCouPon="getCouPonFun($event)"></my-coupons>
		</u-popup>
		<loading-view v-if="showLoading" background-color="rgba(0, 0, 0, .5)" :size="60"></loading-view>
	</view>
</template>

<script>
	import {
		createOrder,
		queryOrderNo,
		orderBuy,
		getOrderCoupon
	} from '@/api/order';
	import {
		getAddressDetail,
	} from '@/api/user';
	import {
		teamBuy
	} from '@/api/activity'
	import {
		prepay,
		getMnpNotice,
		getPayway
	} from '@/api/app';
	import {
		wxpay,
		alipay
	} from '@/utils/pay'
	export default {
		data() {
			return {
				dataSource: {},
				menus: [],
				totalPrice: 0,
				actualPrice: 0,
				orderInfo: {
					order_amount: 0,
					couponAmount: 0
				},
				isFirstLoading: true,
				showLoading: false,
				showCoupon: false,
				address: {},
				addressId: '',
				useIntegral: 0,
				popActive: 0,
				userRemark: '',
				usableCoupon: [],
				unusableCoupon: [],
				couponId: "",
				payWayArr: [],
				payWay: '',
				couponNum: 0,
				bargainLaunchId: -1,
				showPop: false
			};
		},

		onLoad(options) {
			// this.getPaywayFun()
			/* uni.$on("selectaddress", (e) => {
				this.addressId = e.id;
			}) */
			if (!options.data) {
				this.$toast({
					title: '未获取到订单信息，即将返回首页'
				})
				setTimeout(() => uni.switchTab({
					url: '/pages/index/index'
				}), [2000])
				return
			}
			const data = JSON.parse(decodeURIComponent(options.data));
			this.dataSource = data
			this.menus = data.menus
			this.type = data.type
			this.totalPrice = data.totalPrice
			this.actualPrice = data.actualPrice
			this.orderInfo.order_amount = data.totalPrice
			this.addressId = data.addressId
			this.getAddressDetailFun()
		},

		onShow: async function() {
			const {
				order_amount
			} = this.orderInfo
			/* const pages = getCurrentPages();
			const curPage = pages[pages.length - 1];
			const _couponData = curPage.$vm.couponData || {}
			const _order_amount = _couponData.id ? (order_amount * 10000 - _couponData.couponAmount * 10000) / 10000 :
				order_amount
			this.orderInfo = {
				...this.orderInfo,
				..._couponData,
				order_amount: _order_amount < 0 ? 0 : _order_amount
			} */
			await this.getOrderCouponFun();
			if (this.payStatus) return;
			setTimeout(() => {
				this.orderBuyFun();
			}, 100)
		},
		onUnload: function() {
			// uni.$off("selectaddress")
		},
		methods: {
			/* getPaywayFun() {
				return new Promise(resolve => {
					getPayway().then(res => {
						if(res.code == 1) {
							this.payWayArr = res.data
							this.payWay = res.data.length ? res.data[0].pay_way : 0
							resolve()
						}
					})
				})
			}, */
			onChangeNum(e) {
				this.couponNum = e.detail
			},
			getCouPonFun(couponData) {
				if (couponData.id) {
					const {
						totalPrice
					} = this.dataSource
					const _order_amount = parseFloat(
						(totalPrice - couponData.couponAmount).toFixed(2))
					this.orderInfo.order_amount = _order_amount <= 0 ? 0 : _order_amount
					this.orderInfo.couponId = couponData.id
					this.orderInfo.couponAmount = couponData.couponAmount
					this.showPop = false
				} else {
					this.orderInfo.order_amount = this.totalPrice
					this.orderInfo.couponAmount = 0
					delete this.orderInfo.couponId
					this.showPop = false
				}
			},
			// 获取收货地址
			getAddressDetailFun() {
				getAddressDetail(this.addressId).then(res => {
					if (res.code == 200) {
						this.address = res.data;
					}
				});
			},
			onSelectCoupon(e) {
				this.couponId = e
				this.showCoupon = false
				this.orderBuyFun()
			},
			changeShowPop() {
				if (this.couponNum) {
					this.showPop = true
				}
			},
			goPage(url) {
				if (!this.isLogin) return toLogin()
				uni.navigateTo({
					url,
					fail(err) {}
				})
			},
			getAuthMsg() {
				return new Promise(resolve => {
					getMnpNotice({
						scene: 1
					}).then(res => {
						if (res.code == 1) {
							console.log(res.data)
							uni.requestSubscribeMessage({
								tmplIds: res.data,

								fail(res) {
									console.log(res);
								},

								complete() {
									resolve();
								}

							});
						} else {
							resolve();
						}
					});
				});
			},

			onSubmitOrder() {
				uni.showModal({
					title: '温馨提示',
					content: '是否确认下单?',
					confirmColor: '#FF2C3C',
					success: async res => {
						let {
							confirm
						} = res;
						if (confirm) {
							this.showLoading = true
							this.orderBuyFun('submit');
						}
					}
				});
			},

			getOrderCouponFun() {
				return new Promise(resolve => {
					getOrderCoupon({
						goods: this.goods
					}).then(res => {
						if (res.code == 1) {
							const {
								usable,
								unusable
							} = res.data;
							this.usableCoupon = usable,
								this.unusableCoupon = unusable
							resolve();
						}
					});
				});
			},
			async queryOrderNoData(order_no) {
				const {
					code,
					data,
					msg,
				} = await queryOrderNo(order_no)
				if (code === 3000) {
					setTimeout(() => {
						this.queryOrderNoData(order_no)
					}, 1 * 1000)
				} else if (code === 3005) {
					uni.redirectTo({
						url: `/pages/pay_result/pay_result?order_no=${order_no}`
					});
				} else if (code !== 200) {
					this.showLoading = false
					this.$toast({
						title: msg,
						endtime: 4000
					})
				} else {
					this.wxpayData(data, order_no)
				}
			},
			async wxpayData(payData, order_no) {
				wxpay(payData).then((res) => {
					this.showLoading = false
					if (res == 'success') {
						this.payStatus = true;
						uni.redirectTo({
							url: `/pages/pay_result/pay_result?order_no=${order_no}`
						});
					} else {
						this.$toast({
							title: res || '支付失败'
						})
					}
				})
			},
			async orderBuyFun(action = 'info') {
				let {
					address,
					userRemark,
					payWay,
					useIntegral,
					bargainLaunchId,
					orderInfo
				} = this;

				const submitObj = {
					addressId: address.id,
					client: 1,
					menuMealList: this.menus.map(({
						menuMealId,
						quantity
					}) => ({
						menuMealId,
						quantity
					})),
					couponId: orderInfo.couponId,
					price: orderInfo.order_amount
				}
				const {
					code,
					msg,
					data
				} = await createOrder(submitObj)
				if (code !== 200) {
					this.$toast({
						title: msg || '生成预订单失败'
					})
					this.showLoading = false
					return
				}
				uni.setStorageSync('_isConfirmOrder', true)
				this.queryOrderNoData(data)
			}
		},
	}
</script>
<style lang="scss">
	.confirm-contain {
		position: relative;

		&::before,
		&::after {
			content: '';
			position: fixed;
			z-index: 19;
			top: 0;
			width: 100%;
			height: 20rpx;
			background-color: #FFCC46;
		}

		&::after {
			background-color: #fff;
			border-radius: 40rpx 40rpx 0 0;
		}

		.coupon-wrap {
			padding-bottom: 200rpx;
		}
	}

	.confirm-order .confirm-con {
		overflow: hidden;
		padding-bottom: calc(200rpx + env(safe-area-inset-bottom));

		.confirm-address-wrap {
			margin: 20rpx 20rpx 40rpx;

			.address-info {
				background-color: #F7F7F7;
				border-radius: 20rpx;
				overflow: hidden;
				font-size: 24rpx;

				.address-wrap {
					padding: 28rpx;
					font-size: 24rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #4A4A4A;
					line-height: 40rpx;

					.address {
						color: #727272;
						font-size: 20rpx;
						font-weight: 400;
					}
				}

				.time-info {
					padding: 24rpx 28rpx;
					font-size: 24rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #FF8F00;
					line-height: 26rpx;
					background-color: #F0F0F0;
					border-radius: 20rpx;
				}
			}
		}
	}

	.confirm-order .contain {
		border-radius: 14rpx;
		margin: 0 20rpx 0;
		background-color: #fff;
		overflow: hidden;
	}

	.confirm-order .img-line {
		height: 1.5px;
		width: 100%;
		display: block;
	}


	.confirm-order .coupons {
		height: 100rpx;
		padding: 0 24rpx;
	}

	.menus {
		.order-menus {
			.item-wrap {
				margin-bottom: 20rpx;
				background-color: #F7F7F7;
			}
		}

		.title {
			padding: 22rpx 24rpx;
			border-bottom: 1px solid #F6F6F6;
		}

		.shop-icon {
			width: 40rpx;
			height: 40rpx;
		}

		.all-num {
			padding: 22rpx 24rpx;
			border-bottom: 1px dotted #F6F6F6;
		}
	}


	.confirm-order .footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		color: #727272;
		box-sizing: content-box;
		padding-bottom: env(safe-area-inset-bottom);
		background-color: #fff;

		.unit-text {
			transform: translateX(-14rpx);
		}

		.item {
			padding: 14rpx 50rpx;
			background-color: #F7F7F7;
			font-size: 28rpx;
			font-family: PingFangSC-Semibold, PingFang SC;
			font-weight: 600;
			color: #727272;
			line-height: 40rpx;

			.coupon-num {
				font-size: 32rpx;
				font-family: PingFangSC-Semibold, PingFang SC;
				font-weight: 600;
				color: #ff9900;
				line-height: 44rpx;
			}
		}

		.all-price-wrap {
			padding: 12rpx 20rpx 12rpx 50rpx;
			background-color: #FFF3E4;

			.all-price {
				font-size: 28rpx;
				font-family: PingFangSC-Semibold, PingFang SC;
				font-weight: 600;
				color: #727272;
				line-height: 40rpx;
			}

			.primary-wrap {
				margin-left: 14rpx;

				.price-format {
					font-size: 48rpx;
					font-family: PingFangSC-Semibold, PingFang SC;
					font-weight: 600;
					color: #FF6600;

				}

				.amount-wrap {
					font-size: 48rpx;
					font-family: PingFangSC-Semibold, PingFang SC;
					font-weight: 600;
					color: #FF6600;
					line-height: 66rpx;
				}
			}

			.muted {
				font-size: 24rpx;
				font-family: PingFangSC-Semibold, PingFang SC;
				font-weight: 600;
				color: #9B9B9B;
				line-height: 34rpx;

				.amount-wrap {
					font-size: 24rpx;
					color: #9B9B9B;
					line-height: 34rpx;
				}
			}
		}
	}


	.confirm-order .pay-way .title {
		padding: 20rpx 24rpx;
	}

	.confirm-order .pay-way .radio-group .item {
		height: 120rpx;
		padding: 0 24rpx;
	}

	.confirm-order .price {
		padding: 28rpx 20rpx;
	}

	.confirm-order .price .item:not(:last-of-type) {
		margin-bottom: 20rpx;
	}

	.confirm-order .menus>.item,
	.confirm-order .benefit>.item {
		padding: 0 24rpx;
		height: 80rpx;
	}

	.confirm-order .btn {
		padding: 0 100rpx;
		color: #ffffff;
		border-color: #ff9900;
		background-color: #ff9900;
		font-family: PingFangSC-Semibold, PingFang SC;
		font-weight: 500;
	}

	.confirm-order .van-cell:after {
		border: none;
	}

	.pop-title {
		height: 100rpx;
		border-bottom: 1rpx solid #F2F2F2;
	}

	.pop-title .title {
		margin-left: 30rpx;
		font-size: 34rpx;
		font-weight: bold;
		line-height: 36rpx;
	}
</style>
